import React, { useEffect, useState } from 'react'
import type { FC } from 'react'
// antd
import { ConfigProvider } from 'antd'
import 'antd/dist/reset.css'

import zhCN from 'antd/lib/locale/zh_CN'
import enUS from 'antd/lib/locale/en_US'

import AuthRouter from './routes/authRouter'
import Router from './routes/index'

import { getBrowserLang } from '@/utils/util'
import { RootState, useSelector, useDispatch } from './redux'
import { setLanguage } from '@/redux/modules/global'
import i18n from '@/i18n/config'
// App包裹组件
import { App } from 'antd'

const AppEntey: FC = () => {
  const dispatch = useDispatch()
  const { language, assemblySize } = useSelector((state: RootState) => state.global)
  const [i18nLocale, setI18nLocale] = useState(enUS)

  // 设置antd 语言国际化
  const setAntdLanguage = () => {
    if (language && language == 'zh') return setI18nLocale(zhCN)
    if (language && language == 'en') return setI18nLocale(enUS)
    if (getBrowserLang() == 'zh') return setI18nLocale(zhCN)
    if (getBrowserLang() == 'en') return setI18nLocale(enUS)
  }
  useEffect(() => {
    // 根据本地存储的language全局设置i8n
    i18n.changeLanguage(language || getBrowserLang())
    setAntdLanguage()
    dispatch(setLanguage(language || getBrowserLang()))
  }, [language])

  return (
    <ConfigProvider
      theme={{
        token: {
          colorPrimary: '#824C96'
        }
      }}
      locale={i18nLocale}
      componentSize={assemblySize}
    >
      <App>
        <AuthRouter>
          <Router />
        </AuthRouter>
      </App>
    </ConfigProvider>
  )
}

export default AppEntey
